package com.mimiwang.common.aop;

import com.mimiwang.common.annotation.RequireLogin;
import com.mimiwang.common.constant.Constant;
import com.mimiwang.common.constant.HttpStatus;
import com.mimiwang.common.utils.ResponseUtil;
import com.mimiwang.common.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/5/10 22:13
 */

@Component
@Aspect
@Slf4j
public class LoginAspect {

//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut(value = "@annotation(com.mimiwang.common.annotation.RequireLogin) || @within(com.mimiwang.common.annotation.RequireLogin)")
    public void pointCut(){

    }
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinpoint) throws Throwable {
        // 获取方法方法上的LoginValidator注解
        MethodSignature methodSignature = (MethodSignature)joinpoint.getSignature();
        Method method = methodSignature.getMethod();
        RequireLogin loginValidator = method.getAnnotation(RequireLogin.class);
        // 如果有，并且值为false，则不校验
        if (loginValidator != null && !loginValidator.require()) {
            return joinpoint.proceed(joinpoint.getArgs());
        }
        // 正常校验 获取request和response
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null || requestAttributes.getResponse() == null) {
            // 如果不是从前段过来的，没有request，则直接放行
            return joinpoint.proceed(joinpoint.getArgs());
        }
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        // 获取token
        String token = request.getHeader(Constant.TOKEN_HEADER_NAME);
        if (StringUtils.isBlank(token)) {
            log.warn("无token");
            returnNoLogin(response);
            return null;
        }
        try {

            TokenUtil.verify(token);

        } catch (Exception e) {
            e.printStackTrace();
            log.warn("token验证失败");
            returnNoLogin(response);
            return null;
        }
        // 放行
        return joinpoint.proceed(joinpoint.getArgs());
    }

    /**
     * 返回未登录的错误信息
     * @param response ServletResponse
     */
    private void returnNoLogin(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        // 设置返回401 和响应编码
        response.setStatus(401);
        response.setContentType("Application/json;charset=utf-8");
        // 构造返回响应体
        String s = ResponseUtil.errorJSONData(HttpStatus.UNAUTHORIZED.getCode(), HttpStatus.UNAUTHORIZED.getMsg());

        outputStream.write(s.getBytes(StandardCharsets.UTF_8));
    }

}
